jQuery(function($) {

    showRevendedorDiv();
    addMask($('td.valorunitario input'), 'money-db');
    $('input[type="text"]').setMask();
    updateValorSugerido("td.valorunitario input", "td.quantidade input", "td.valortotal");
    addLiveEvent(".ui-menu-item a", "input.ui-autocomplete-input", "input.ui-autocomplete-input");

    $("#id_cep").live("focusout", function() {
        console.log(this.value);
        getAddress(this.value);
    });

    $("input[name=pessoa]").click(function() {
        if(this.value == 1) {
            alternateFields($(".inscricaoestadual"), $(".rg"));
            clearFields($(".inscricaoestadual").find("input"));
        } else if (this.value == 0) {
            alternateFields($(".rg"), $(".inscricaoestadual"));
            clearFields($(".rg").find("input"));
        }
    });


    $("input[name=tipo]").click(function() {
        showRevendedorDiv();
    });

    (function() {
        $("input[name=pessoa]:checked").click();

//        $(".add-another").attr("onclick", "return showAddAnotherModal(this);");

//        $("#modalCloseIcon").live("click", function() {
//            closeModal(this);
//        });


    })();
});

    function addMask(object, mask) {
        object.live("focus", function() {
            $(this).attr('alt', mask);
            $('input[type="text"]').setMask();
        });
    }

    function updateValorSugerido(inputField1, inputField2, output) {
        $(inputField1).live("focusout", function() {
            refreshValues(inputField1, inputField2, output);
        });
        $(inputField2).live("focusout", function() {
            refreshValues(inputField1, inputField2, output);
        });
    }

    function addLiveEvent(selectorClick, selectorKeypress, target) {
        $(selectorKeypress).live("keypress", function(event) {
            if (event.which == 13) {
                $(target).hide().next().hide();
            }
        });

        $(selectorClick).live("click", function() {
            $(target).hide().next().hide();
        });

        $(".ui-icon-trash").live("click", function() {
            $(target).show().next().show();
        })
    }

    function refreshValues(in1, in2, out) {
        var valor1 = $(in1).val();
        var valor2 = $(in2).val().trim() === "" ? 0 : $(in2).val();
        var retorno = valor1 * valor2;
        $(out).html("<p>" + retorno.toFixed(2) + "</p>");
    }

    function showRevendedorDiv() {
        var tipoPessoa = document.getElementsByName("tipo");

        for (var i = 0; i < tipoPessoa.length; i++) {
            if (tipoPessoa[i].parentNode.textContent.replace(/^\s+|\s+$/g,"") == "Revendedor") {
                if (tipoPessoa[i].checked) {
                    $(".limitecompra").show();
                } else {
                    $(".limitecompra").hide();
                    clearFields($(".limitecompra").find("input"))
                }
            }
        }

    }

    function getAddress(cep) {

        $.ajax({
            type: "POST",
            url: "http://www.republicavirtual.com.br/web_cep.php",
            dataType: "jsonp",
            crossDomain: true,
            data: {
                formato: "javascript",
                cep: cep
            },
            beforeSend: function() {
              console.log("\nLoading\n");
            },
            complete: function() {
                console.log("\n\nO bairro de meu fi: " + resultadoCEP.bairro);
            }
        });
    };

    function alternateFields(toHide, toShow) {
        toHide.hide();
        toShow.show();
    }

    function clearFields(inputs) {
        for (var i = 0; i < inputs.length; i++) {
            inputs[i].value = "";
        }
    }


